package com.cinema;

import org.apache.commons.cli.*;
import com.cinema.cli.SessionManager;
import com.cinema.entity.User;
import com.cinema.entity.Role;
import com.cinema.service.CinemaService;

public class CinemaCLI {
    public static void main(String[] args) {
        Options options = new Options();

        // 用户登录/登出
        options.addOption(Option.builder().longOpt("login").desc("用户登录").build());
        options.addOption(Option.builder().longOpt("logout").desc("用户登出").build());
        options.addOption(Option.builder().longOpt("user").hasArg().desc("用户名/用户ID").build());
        options.addOption(Option.builder().longOpt("password").hasArg().desc("密码").build());

        // 用户管理
        options.addOption(Option.builder().longOpt("add-user").desc("添加用户").build());
        options.addOption(Option.builder().longOpt("delete-user").desc("删除用户").build());
        options.addOption(Option.builder().longOpt("update-user").desc("修改用户").build());
        options.addOption(Option.builder().longOpt("id").hasArg().desc("用户ID/对象ID").build());
        options.addOption(Option.builder().longOpt("username").hasArg().desc("用户名").build());
        options.addOption(Option.builder().longOpt("role").hasArg().desc("角色").build());
        options.addOption(Option.builder().longOpt("superior").hasArg().desc("上级ID").build());

        // 电影管理
        options.addOption(Option.builder().longOpt("add-movie").desc("添加电影").build());
        options.addOption(Option.builder().longOpt("list-movies").desc("查询所有电影").build());
        options.addOption(Option.builder().longOpt("name").hasArg().desc("名称").build());
        options.addOption(Option.builder().longOpt("duration").hasArg().desc("时长").build());

        // 放映厅管理
        options.addOption(Option.builder().longOpt("add-room").desc("添加放映厅").build());
        options.addOption(Option.builder().longOpt("delete-room").desc("删除放映厅").build());
        options.addOption(Option.builder().longOpt("list-rooms").desc("查询所有放映厅").build());
        options.addOption(Option.builder().longOpt("rows").hasArg().desc("行数").build());
        options.addOption(Option.builder().longOpt("cols").hasArg().desc("列数").build());

        // 排片管理
        options.addOption(Option.builder().longOpt("add-schedule").desc("添加排片").build());
        options.addOption(Option.builder().longOpt("delete-schedule").desc("删除排片").build());
        options.addOption(Option.builder().longOpt("list-schedules").desc("查询所有排片").build());
        options.addOption(Option.builder().longOpt("movie").hasArg().desc("电影ID").build());
        options.addOption(Option.builder().longOpt("room").hasArg().desc("放映厅ID").build());
        options.addOption(Option.builder().longOpt("start").hasArg().desc("开始时间").build());
        options.addOption(Option.builder().longOpt("end").hasArg().desc("结束时间").build());

        // 售票
        options.addOption(Option.builder().longOpt("sell-ticket").desc("售票").build());
        options.addOption(Option.builder().longOpt("schedule").hasArg().desc("排片ID").build());
        options.addOption(Option.builder().longOpt("row").hasArg().desc("行号").build());
        options.addOption(Option.builder().longOpt("col").hasArg().desc("列号").build());
        options.addOption(Option.builder().longOpt("phone").hasArg().desc("手机号").build());

        // 查询
        options.addOption(Option.builder().longOpt("seat-status").desc("查询排片座位状态").build());
        options.addOption(Option.builder().longOpt("seat-statistics").desc("查询排片座位统计").build());
        options.addOption(Option.builder().longOpt("current-movies").desc("查询当前上映电影").build());
        options.addOption(Option.builder().longOpt("query-schedule-by-movie").desc("按电影名称查询排片").build());
        options.addOption(Option.builder().longOpt("query-schedule-by-room").desc("按放映厅查询排片").build());
        options.addOption(Option.builder().longOpt("query-schedule-by-time").desc("按时间范围查询排片").build());

        // 帮助
        options.addOption(Option.builder().longOpt("help").desc("显示帮助信息").build());

        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();
        CinemaService service = new CinemaService();
        try {
            CommandLine cmd = parser.parse(options, args);
            if (cmd.hasOption("help") || args.length == 0) {
                formatter.printHelp("cinema.jar [options]", options);
                return;
            }
            // 登录
            if (cmd.hasOption("login")) {
                String userId = cmd.getOptionValue("user");
                // 这里简化为只需userId，无密码校验
                if (userId == null) {
                    System.out.println("请指定--user参数");
                    return;
                }
                SessionManager.saveSession(userId);
                System.out.println("登录成功，当前用户：" + userId);
                return;
            }
            // 登出
            if (cmd.hasOption("logout")) {
                SessionManager.clearSession();
                System.out.println("已登出");
                return;
            }
            // 读取session
            String sessionUserId = SessionManager.loadSession();
            if (sessionUserId == null) {
                System.out.println("请先登录 (--login --user xxx)");
                return;
            }
            User operator = service.getUser(sessionUserId);
            if (operator == null) {
                System.out.println("当前session用户不存在，请重新登录");
                SessionManager.clearSession();
                return;
            }
            // 用户管理（已实现）
            if (cmd.hasOption("add-user")) {
                String id = cmd.getOptionValue("id");
                String username = cmd.getOptionValue("username");
                String roleStr = cmd.getOptionValue("role");
                String superior = cmd.getOptionValue("superior");
                Role role = roleStr != null ? Role.valueOf(roleStr) : null;
                User user = new User(id, username, role, superior);
                service.addUser(operator, user);
                System.out.println("添加用户成功");
                return;
            }
            if (cmd.hasOption("delete-user")) {
                String id = cmd.getOptionValue("id");
                service.deleteUser(operator, id);
                System.out.println("删除用户成功");
                return;
            }
            if (cmd.hasOption("update-user")) {
                String id = cmd.getOptionValue("id");
                String username = cmd.getOptionValue("username");
                String roleStr = cmd.getOptionValue("role");
                String superior = cmd.getOptionValue("superior");
                Role role = roleStr != null ? Role.valueOf(roleStr) : null;
                User user = new User(id, username, role, superior);
                service.updateUser(operator, user);
                System.out.println("修改用户成功");
                return;
            }
            // 放映厅删除
            if (cmd.hasOption("delete-room")) {
                String id = cmd.getOptionValue("id");
                service.deleteRoom(operator, id);
                System.out.println("删除放映厅成功");
                return;
            }
            // 排片删除
            if (cmd.hasOption("delete-schedule")) {
                String id = cmd.getOptionValue("id");
                service.deleteSchedule(operator, id);
                System.out.println("删除排片成功");
                return;
            }
            // 电影管理
            if (cmd.hasOption("add-movie")) {
                String id = cmd.getOptionValue("id");
                String name = cmd.getOptionValue("name");
                String durationStr = cmd.getOptionValue("duration");
                int duration = durationStr != null ? Integer.parseInt(durationStr) : 0;
                service.addMovie(operator, new com.cinema.entity.Movie(id, name, duration));
                System.out.println("添加电影成功");
                return;
            }
            if (cmd.hasOption("list-movies")) {
                service.getAllMovies().forEach(System.out::println);
                return;
            }
            // 放映厅管理
            if (cmd.hasOption("add-room")) {
                String id = cmd.getOptionValue("id");
                String name = cmd.getOptionValue("name");
                int rows = Integer.parseInt(cmd.getOptionValue("rows"));
                int cols = Integer.parseInt(cmd.getOptionValue("cols"));
                service.addRoom(operator, new com.cinema.entity.ScreeningRoom(id, name, rows, cols));
                System.out.println("添加放映厅成功");
                return;
            }
            if (cmd.hasOption("list-rooms")) {
                service.getAllRooms().forEach(System.out::println);
                return;
            }
            // 排片管理
            if (cmd.hasOption("add-schedule")) {
                String id = cmd.getOptionValue("id");
                String movieId = cmd.getOptionValue("movie");
                String roomId = cmd.getOptionValue("room");
                String start = cmd.getOptionValue("start");
                String end = cmd.getOptionValue("end");
                com.cinema.entity.Movie movie = service.getMovie(movieId);
                com.cinema.entity.ScreeningRoom room = service.getRoom(roomId);
                java.time.format.DateTimeFormatter fmt = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                java.time.LocalDateTime startTime = java.time.LocalDateTime.parse(start, fmt);
                java.time.LocalDateTime endTime = java.time.LocalDateTime.parse(end, fmt);
                service.addSchedule(operator, new com.cinema.entity.Schedule(id, movie, room, startTime, endTime));
                System.out.println("添加排片成功");
                return;
            }
            if (cmd.hasOption("list-schedules")) {
                service.getAllSchedules().forEach(System.out::println);
                return;
            }
            // 售票
            if (cmd.hasOption("sell-ticket")) {
                String scheduleId = cmd.getOptionValue("schedule");
                int row = Integer.parseInt(cmd.getOptionValue("row"));
                int col = Integer.parseInt(cmd.getOptionValue("col"));
                String phone = cmd.getOptionValue("phone");
                boolean result = service.sellTicket(operator, scheduleId, row, col, phone);
                System.out.println(result ? "售票成功" : "售票失败");
                return;
            }
            // 查询
            if (cmd.hasOption("seat-status")) {
                String scheduleId = cmd.getOptionValue("schedule");
                String[][] status = service.getSeatStatus(scheduleId);
                if (status == null) {
                    System.out.println("排片不存在");
                } else {
                    for (int i = 0; i < status.length; i++) {
                        for (int j = 0; j < status[i].length; j++) {
                            System.out.print((status[i][j] == null ? "O" : "X") + " ");
                        }
                        System.out.println();
                    }
                }
                return;
            }
            if (cmd.hasOption("seat-statistics")) {
                String scheduleId = cmd.getOptionValue("schedule");
                System.out.println(service.getSeatStatistics(scheduleId));
                return;
            }
            if (cmd.hasOption("current-movies")) {
                service.getCurrentMovies().forEach(System.out::println);
                return;
            }
            if (cmd.hasOption("query-schedule-by-movie")) {
                String name = cmd.getOptionValue("name");
                service.queryByMovie(name).forEach(System.out::println);
                return;
            }
            if (cmd.hasOption("query-schedule-by-room")) {
                String roomId = cmd.getOptionValue("room");
                service.queryByRoom(roomId).forEach(System.out::println);
                return;
            }
            if (cmd.hasOption("query-schedule-by-time")) {
                String start = cmd.getOptionValue("start");
                String end = cmd.getOptionValue("end");
                java.time.format.DateTimeFormatter fmt = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                java.time.LocalDateTime startTime = java.time.LocalDateTime.parse(start, fmt);
                java.time.LocalDateTime endTime = java.time.LocalDateTime.parse(end, fmt);
                service.queryByTime(startTime, endTime).forEach(System.out::println);
                return;
            }
            System.out.println("命令行参数解析成功，未匹配到具体命令。");
        } catch (Exception e) {
            System.err.println("命令执行错误: " + e.getMessage());
            formatter.printHelp("cinema.jar [options]", options);
        }
    }
} 